package com.apesay.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.apesay.service.auth.AccountService;
import com.apesay.service.base.ClientService;
import com.apesay.utils.Constant;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/account")
public class AccountController extends RestController{
	@Autowired
	private AccountService accountService;
	@Autowired
	private ClientService clientService;
	@Resource
	private HttpSession session;
	
	@RequiresAuthentication
	@RequestMapping("/manage")
	public String manage(){
		return "account/manage";
	}
	@RequiresAuthentication
	@RequestMapping("/add")
	public String add(){
		return "account/add";
	}
	@RequiresAuthentication
	@RequestMapping("/edit")
	public String edit(String objectId,Model model){
		model.addAttribute(Constant.OBJECTID, objectId);
		return "account/edit";
	}
	@RequiresAuthentication
	@RequestMapping("/getCurrentUser")
	public @ResponseBody JSONObject getCurrentUser(){
		Object userObj = session.getAttribute("currentaccount");//当前登录用户
		JSONObject user = JSON.parseObject(userObj.toString());
		String userid = user.getString(Constant.OBJECTID);
		return clientService.getObjectById(getModel(),userid).getJSONObject(Constant.RESULT);
	}
	
	public JSONObject save(@RequestBody String body){
		return accountService.saveAccount(JSON.parseObject(body));
	}
	
	public JSONObject update(@PathVariable String id,@RequestBody String body){
		JSONObject bodyObj = JSON.parseObject(body);
		Object userObj = session.getAttribute("currentaccount");//当前登录用户
		JSONObject reObject = new JSONObject();
		JSONObject jsonObject=JSON.parseObject(body);
		if("true".equals(jsonObject.getString("isChangePass"))){//修改密码
			reObject = accountService.changePass(bodyObj,userObj);
		}else if("true".equals(jsonObject.getString("isRePass"))){//重置密码 默认123456
			reObject = accountService.rePass(id);
		}else{
			jsonObject.remove("password");
			reObject = accountService.updateAccount(id, bodyObj);
		}
		return reObject;
	}
	
	public JSONObject delete(@PathVariable String id){
		return accountService.delAccount(id);
	}
	
	@Override
	protected String getModel() {
		return Constant.model_backend_account;
	}
}
